package it.unibz.easytravel.travel;


import it.unibz.easytravel.common.Person;
import it.unibz.easytravel.db.PersonDbAdapter;
import it.unibz.easytravel.db.TravellersDbAdapter;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.util.Log;

public class Travel {

	private int travelId;
	private String title;
	private String description;
	private Person creator;
	private List<Person> travellers;
	
	
	public Travel(int travelId, String title, String description, int creator_id, Activity activity) {
		this.travelId = travelId;
		this.title = title;
		this.description = description;
		this.travellers = new ArrayList<Person>();
		
		PersonDbAdapter mPersonAdapter = new PersonDbAdapter(activity);
		TravellersDbAdapter mTrvellersAdapter = new TravellersDbAdapter(activity);
		mPersonAdapter.open();
		mTrvellersAdapter.open();
		
		//adds travel creator
		Cursor curPersons = mPersonAdapter.getPersonInfo(creator_id);
		if (curPersons.moveToFirst()) {
			this.creator = new Person(curPersons.getString(curPersons.getColumnIndexOrThrow(PersonDbAdapter.NAME)),
					curPersons.getString(curPersons.getColumnIndexOrThrow(PersonDbAdapter.PHONE_NUMBER)));
		}else{
			throw new RuntimeException("creator does not exsist Travel.Constructor");
		}
		
		
		//adds travellers
		Cursor curTravellers = mTrvellersAdapter.getTravellers(travelId);
		int preson_id;
		while (curTravellers.moveToNext()) {
			preson_id = curTravellers.getInt(curTravellers.getColumnIndexOrThrow(TravellersDbAdapter.PERSON_ID));
			Log.i("constructor", preson_id+"");
			
			curPersons = mPersonAdapter.getPersonInfo(preson_id);
			if(curPersons.moveToNext()){
				travellers.add(new Person(
						curPersons.getString(curPersons.getColumnIndexOrThrow(PersonDbAdapter.NAME)),
						curPersons.getString(curPersons.getColumnIndexOrThrow(PersonDbAdapter.PHONE_NUMBER))
					    ));
			}else{
				throw new RuntimeException("creator does not exsist Travel.Constructor2");
			}
		}
		

		mPersonAdapter.close();
		mTrvellersAdapter.close();
	}
	
	public Travel(int travelId, String title, String description, Person creator, List<Person> travellers) {
		this.travelId = travelId;
		this.title = title;
		this.description = description;
		this.creator = creator;		
		this.travellers = new ArrayList<Person>();
		this.travellers = travellers;
	}
	
	public void addTraveler(Person traveller) {
		travellers.add(traveller);
	}
	
	public List<Person> getTravellers() {
		return travellers;
	}
	
	public String getTitle(){
		return title;
	}
	
	public String getDescription(){
		return description;
	}
	
	public Person getCreator(){
		return creator;
	}
	
	public int getTravelId(){
		return travelId;
	}
}
